<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>条件渲染之TODOlist</title>
  </head>
  <body>
    <h2>条件渲染之TODOlist</h2>
    <div id="todoListApp">
      <form action="" v-on:submit.prevent="addNewTodo">
        <label for="new-todo">Add a todo</label>
        <input
          type="text"
          id="new-todo"
          v-model="newTodoText"
          placeholder="E.g. Feed the cat"
        />
        <button>Add</button>
      </form>
      <ul>
        <todo-item
          v-for="(item, index) of todos"
          :key="item.id"
          :title="item.title"
          @remove="todos.splice(index, 1)"
        ></todo-item>
      </ul>
    </div>
    <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
    <script>
      Vue.component("todo-item", {
        template: `<li>{{ title }}<button v-on:click="$emit('remove')">Delete</button></li>`,
        props: ["title"]
      });
      var todoListApp = new Vue({
        el: "#todoListApp",
        data: {
          newTodoText: "",
          todos: [
            {
              id: 1,
              title: "Do the dishes"
            },
            {
              id: 2,
              title: "Take out the trash"
            },
            {
              id: 3,
              title: "Mow the lawn"
            }
          ],
          nextTodoId: 4
        },
        methods: {
          addNewTodo: function() {
            if (!this.newTodoText) return;
            this.todos.push({
              id: this.nextTodoId++,
              title: this.newTodoText
            });
            this.newTodoText = "";
          },
          deleteTodo: function(index) {
            this.todos.splice(index, 1);
          }
        }
      });
    </script>
  </body>
</html>
